package wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 2 * @Author: 王杰
 * 3 * @Date: 2020/11/11 14:46
 * 4
 */
public class wordcount {
    public static void main(String[] args) throws Exception {
        //1：获取流处理运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2：构建socket流数据源，并指定IP地址和端口号
        DataStream<String> lines = env.socketTextStream("node01", 9999);

        //3：对接收到的数据进行空格拆分
        SingleOutputStreamOperator<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> out) throws Exception {
                //切分
                String[] words = line.split(" ");
                for (String word : words) {
                    //输出
                    out.collect(word);
                }
            }
        });

        //4：对拆分后的单词，每个单词记一次数
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne =
                words.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String word) throws Exception {
                return Tuple2.of(word, 1);
            }
        });

        //5：对拆分后的单词进行分组
        KeyedStream<Tuple2<String, Integer>, Tuple> groupedStream = wordAndOne.keyBy(0);

        //6：根据单词的次数进行聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> summed = groupedStream.sum(1);

        //7：打印输出
        summed.print();

        //8：启动执行
        env.execute("StreamWordCount");

    }
}
